/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * This class represents a target that someone claimed
 * 
 * 
 */
public class ClaimedTarget implements BotObject {
   /**
    * Removes the specified claimed target, or leaves it claimed by no one, signifying that it's been hit
    * 
    * @param args
    *           Determines which user to remove/update the claim for
    * @return
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("DELETE FROM claim WHERE claimedby = ? AND timeshit = 0");
		 ps.setString(1, args[0]);
		 if (ps.executeUpdate() == 1) {
			out = true;
		 } else {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("UPDATE claim SET claimedby = '' WHERE claimedby = ?");
			ps.setString(1, args[0]);
			if (ps.executeUpdate() == 1) {
			   out = true;
			}
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all claimed targets
    * 
    * @return List of ClaimedTarget objects
    */
   public static List<ClaimedTarget> getClaimed() {
	  List<ClaimedTarget> out = new LinkedList<ClaimedTarget>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM claim");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out.add(new ClaimedTarget(rs.getString("target"), rs.getString("claimedby"), rs.getInt("timeshit")));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String target = "";

   private String claimedBy = "";

   private int timesHit = 0;

   public ClaimedTarget(final String target, final String claimedBy, final int timesHit) {
	  this.target = target;
	  this.claimedBy = claimedBy;
	  this.timesHit = timesHit;
   }

   public String getClaimedBy() {
	  return claimedBy;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (StringTools.isNullOrEmpty(getTarget()) || getClaimedBy() == null)
		 return out;
	  if ("".equals(getClaimedBy())) {
		 out.add(Colors.BLUE + getTarget() + Colors.RED + " (hit " + getTimesHit() + " times)");
	  } else {
		 out.add(Colors.BLUE + getTarget() + Colors.RED + " (" + getClaimedBy() + ")");
	  }
	  return out;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getTarget()) || getClaimedBy() == null)
		 return out;
	  out.put("Target", getTarget());
	  out.put("Claimed By", getClaimedBy());
	  out.put("Times Hit", getTimesHit());
	  return out;
   }

   public String getTarget() {
	  return target;
   }

   public int getTimesHit() {
	  return timesHit;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getTarget()) || getClaimedBy() == null)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 deleteFromDB(getClaimedBy());

		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO claim VALUES(?,?,?)");
		 ps.setString(1, getTarget());
		 ps.setString(2, getClaimedBy());
		 ps.setInt(3, getTimesHit());
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (SQLException e) {
		 }
	  }
	  return out;
   }

   public void setTimesHit(final int timesHit) {
	  this.timesHit = timesHit;
   }
}
